package com.wms.common.utils;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 线程相关的工具类
 */
public class Threads {
    private static final Logger logger = LoggerFactory.getLogger(Threads.class);

    /**
     * 让当前线程睡眠指定的毫秒数
     *
     * @param milliseconds
     */
    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            return;
        }
    }

    /**
     * 优雅地关闭线程池，确保所有任务完成，超时后强制关闭
     *
     * @param pool
     */
    public static void shutdownAndAwaitTermination(ExecutorService pool) {
//        检查线程池是否为空以及是否已经关闭
        if (pool != null && !pool.isShutdown()) {
//            关闭线程池，不再接收新任务
            pool.shutdown();
            try {
//                等待线程池中的任务完成，最多等待120秒
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
//                    强制终止所有任务
                    pool.shutdownNow();
                    if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                        logger.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
//                强制关闭线程池，并恢复当前线程的中断状态
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * 打印线程异常信息
     *
     * @param r
     * @param t
     */
    public static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            logger.error(t.getMessage(), t);
        }
    }
}
